using B.S.XZYData.Api.Wrter.Application.Command.Route;
using B.S.XZYData.ErrorCode;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;

namespace B.S.XZYData.Api.Wrter.Controllers
{
    /// <summary>
    /// 工艺路线写操作控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class RouteController : ControllerBase
    {
        private readonly IMediator _mediator;

        public RouteController(IMediator mediator)
        {
            _mediator = mediator;
        }

        /// <summary>
        /// 保存工艺路线（主表+子表一起保存）
        /// </summary>
        /// <param name="command">保存工艺路线命令</param>
        /// <returns>返回工艺路线ID</returns>
        [HttpPost("save")]
        public async Task<ApiResult<int>> SaveRoute([FromBody] SaveRouteCommand command)
        {
            return await _mediator.Send(command);
        }

        /// <summary>
        /// 添加工艺路线（新增专用接口）
        /// </summary>
        /// <param name="command">添加工艺路线命令</param>
        /// <returns>返回工艺路线ID</returns>
        [HttpPost("add")]
        public async Task<ApiResult<int>> AddRoute([FromBody] AddRouteCommand command)
        {
            return await _mediator.Send(command);
        }

        /// <summary>
        /// 添加工艺路线工序
        /// </summary>
        /// <param name="command">添加工艺路线工序命令</param>
        /// <returns>返回工序ID</returns>
        [HttpPost("add-step")]
        public async Task<ApiResult<int>> AddRouteStep([FromBody] AddRouteStepCommand command)
        {
            return await _mediator.Send(command);
        }

        /// <summary>
        /// 删除工艺路线
        /// </summary>
        /// <param name="command">删除工艺路线命令</param>
        /// <returns>删除结果</returns>
        [HttpDelete("delete")]
        public async Task<ApiResult<bool>> DeleteRoute([FromBody] DeleteRouteCommand command)
        {
            return await _mediator.Send(command);
        }

        /// <summary>
        /// 批量删除工序
        /// </summary>
        /// <param name="command">批量删除工序命令</param>
        /// <returns>删除结果</returns>
        [HttpDelete("delete-steps")]
        public async Task<ApiResult<bool>> DeleteRouteSteps([FromBody] DeleteRouteStepsCommand command)
        {
            return await _mediator.Send(command);
        }

        /// <summary>
        /// 批量删除工艺路线
        /// </summary>
        /// <param name="command">批量删除工艺路线命令</param>
        /// <returns>批量删除结果</returns>
        [HttpDelete("batch-delete")]
        public async Task<ApiResult<BatchDeleteRouteResult>> BatchDeleteRoute([FromBody] BatchDeleteRouteCommand command)
        {
            return await _mediator.Send(command);
        }

        /// <summary>
        /// 导出工艺路线
        /// </summary>
        /// <param name="command">导出工艺路线命令</param>
        /// <returns>Excel文件</returns>
        [HttpPost("export")]
        public async Task<IActionResult> ExportRoute([FromBody] ExportRouteCommand command)
        {
            var result = await _mediator.Send(command);
            if (result.Code == ApiEnum.Success && result.Data != null && result.Data.Length > 0)
            {
                var fileName = $"工艺路线导出_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
                return File(result.Data, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
            }
            return BadRequest(result);
        }

        /// <summary>
        /// 导入工艺路线
        /// </summary>
        /// <param name="file">Excel文件</param>
        /// <param name="operateBy">操作人</param>
        /// <returns>导入结果</returns>
        [HttpPost("import")]
        public async Task<ApiResult<ImportRouteResult>> ImportRoute(IFormFile file, [FromForm] string operateBy)
        {
            if (file == null || file.Length == 0)
            {
                return new ApiResult<ImportRouteResult> { Msg = "请选择要导入的文件", Code = ApiEnum.Fail, Data = new ImportRouteResult() };
            }

            if (!Path.GetExtension(file.FileName).Equals(".xlsx", StringComparison.OrdinalIgnoreCase))
            {
                return new ApiResult<ImportRouteResult> { Msg = "只支持.xlsx格式的文件", Code = ApiEnum.Fail, Data = new ImportRouteResult() };
            }

            using var stream = new MemoryStream();
            await file.CopyToAsync(stream);
            
            var command = new ImportRouteCommand
            {
                FileBytes = stream.ToArray(),
                FileName = file.FileName,
                OperateBy = operateBy
            };

            return await _mediator.Send(command);
        }


    }
} 